<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
          <el-header v-if="routeid" style="height: 40px;">
          <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{routename}}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb>
        </el-header>
        <el-row :gutter="20">
          <!-- 左侧查询 -->
          <el-col :span="18">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="目录名称">
              <el-input v-model="formInline.directoryName" placeholder="目录名称" @keyup.delete.native="inputDelete"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="formInline.state" placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="clear">清除</el-button>
              <el-button type="primary" @click="search">搜索</el-button>
            </el-form-item>
          </el-form>
          </el-col>
          <!-- 新增 -->
          <el-col :span="6" style="text-align: right;">
            <el-button type="text" icon="el-icon-back" @click="$router.push('/subjects/list')" v-if="routeid">返回学科</el-button>
            <el-button type="success" icon="el-icon-edit" @click="addDirectory">新增目录</el-button>
          </el-col>
        </el-row>
        <!-- 总条数 -->
         <el-alert
            :title="String(`数据一共 ${total} 条`)" type="info" show-icon :closable="false"></el-alert>
          <!-- 表单 -->
          <el-table :data="displayList" style="width: 100%" border>
          <el-table-column label="序号" width="80" type="index" :index="indexMethod"/>
          <el-table-column label="所属学科" prop="subjectName"/>
          <el-table-column label="目录名称" prop="directoryName"/>
          <el-table-column label="创建者" prop="username"/>
          <el-table-column label="创建日期" prop="addDate">
            <template #default="{ row }">
              {{ formateTime(row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column label="面试题数量" prop="totals"/>
          <el-table-column label="状态" prop="state" :formatter="formatterFormOfEmpment"/>
          <el-table-column label="操作">
            <!-- #default="{ row }" -->
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="clickSwitch(row)"
              >{{row.state==1?'禁用':'启用'}}</el-button>
              <el-button
               :disabled="row.state==1? false:true"
                type="text"
                size="small"
                @click="clickModify(row)"
              >修改</el-button>
              <el-button
              :disabled="row.state==1? false:true"
                type="text"
                size="small"
                @click="clickRemove(row)"
              >删除</el-button>
            </template>
            </el-table-column>
          </el-table>
        <!-- 分页组件 -->
        <!-- current-page表示的当前页 -->
        <!-- page-sizes:供我们下拉选择的页容量 -->
        <!-- pagesize:表示当前页容量（一般和page-sizes数组中的第一个值是对应的） -->
        <!-- layout：表示分页的样式展示 -->
        <!-- total表示的是一共有多少条数据 -->
        <!-- @size-change：当每页页容量发生变化时触发 -->
        <!-- @current-change ：页码发生变化时触发 -->
        <div  style="margin:10px;display:flex;justify-content:flex-end">
          <el-pagination
             background
            :current-page="listData.page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="listData.pagesize"
            layout="sizes,prev,pager,next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <!-- 弹框 -->
        <el-dialog :title="showTitle" :visible.sync="showDialog" width="360px" :close-on-click-modal="false" @close="closeDialog">
            <el-form :model="form" :rules="rules" ref="directoryForm" >
               <el-form-item label="所属学科" :label-width="formLabelWidth" prop="subjectID" v-if="routeformid">
                <el-select v-model="form.subjectID" placeholder="请选择">
                  <el-option
                  v-for="item in formList.items"
                  :key="item.id"
                  :label="item.subjectName"
                  :value="item.id"
                   ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="目录名称" :label-width="formLabelWidth" prop="directoryName">
                <el-input v-model="form.directoryName"  placeholder="请输入目录名称"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: right;">
              <el-button @click="showDialog = false">取 消</el-button>
              <el-button type="primary" @click="ConfirmAddDirectory">确 定</el-button>
            </div>
          </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list as getDirectorys, add as AddDirectorys, update as ModifyDirectorys, remove as RemoveDirectorys, changeState as changeStateApi } from '@/api/hmmm/directorys'
import { list as getSubjects } from '@/api/hmmm/subjects'
import dayjs from 'dayjs'
export default {
  created () {
    // this.getCompanysList()
    // this.getQuestionList()
    this.getDirectorysList()
    this.getSubjectsList()
    // this.detailApiList()
  },
  data () {
    return {
      listData: {
        page: 1,
        pagesize: 10,
        directoryName: ''
      },
      total: 0,
      formInline: {
        directoryName: '',
        state: ''
      },
      list: [],
      displayList: [],
      // screenList:[], //筛选后的数据
      // listAll:[],
      form: {
        subjectID: '',
        directoryName: ''
      },
      formList: [],
      showDialog: false,
      formLabelWidth: '103px',
      routeid: false,
      routeformid: true,
      routename: '',
      rules: {
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        subjectID: [
          { required: true, message: '请选择所属学科', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    showTitle () {
      return this.form.id ? '修改目录' : '添加目录'
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler () {
        this.sortDirectorys()
      }
    }
  },
  methods: {
    /**
     * 学科跳转
     */
    sortDirectorys () {
      if (this.$route.query.id) {
        this.listData.subjectID = this.$route.query.id
        this.getDirectorysList()
        this.routeid = true
        this.routeformid = false
        this.routename = this.$route.query.name
        this.form.subjectID = Number(this.$route.query.id)
        this.form.directoryName = this.$route.query.name
      } else {
        this.listData = {
          page: 1,
          pagesize: 10,
          directoryName: ''
        }
        this.getDirectorysList()
        this.routeid = false
        this.routeformid = true
      }
    },
    /**
     * 清除
     */
    clear () {
      this.formInline = {
        directoryName: '',
        state: ''
      }
      this.listData = {
        page: 1,
        pagesize: 10,
        directoryName: ''
      }
    },
    /**
     * 监听键盘回退
     */
    inputDelete () {
      this.formInline.directoryName = ''
      this.listData = {
        page: 1,
        pagesize: 10,
        directoryName: ''
      }
    },
    /**
       * 搜索
       */
    search () {
      const name = this.formInline.directoryName
      const state = this.formInline.state
      if (name !== '') {
        this.listData.directoryName = name
        this.getDirectorysList()
      }
      if (name === '' && state !== '') {
        this.listData.state = state
        this.getDirectorysList()
        // this.listData.page = 1
      }
      if (name !== '' && state !== '') {
        this.listData.directoryName = name
        this.listData.state = state
        this.getDirectorysList()
      }
      if (name === '' && state === '') {
        if (this.$route.query.id) {
          this.sortDirectorys()
        }
        this.getDirectorysList()
      }
    },
    /**
       * 删除
       */
    clickRemove (row) {
      this.$confirm('确定删除吗？', '提示').then(async () => {
        await RemoveDirectorys(row)
        this.$message.success('删除成功')
        this.getDirectorysList()
      }).catch(() => {})
    },
    /**
       * 点击修改数据回显
       */
    async clickModify (row) {
      this.showDialog = true
      this.form = { ...row }
    },
    /**
       * 启用/禁用
       */
    async clickSwitch (row) {
      if (row.state === 0) {
        row.state = 1
      } else {
        row.state = 0
      }
      await changeStateApi(row)
      this.$message.success('操作成功')
    },
    /**
       * 添加目录/修改目录
       */
    ConfirmAddDirectory () {
      this.$refs.directoryForm.validate(async (flag) => {
        if (!flag) return
        if (this.form.id) {
          await ModifyDirectorys(this.form)
          this.$message.success('修改成功')
        } else {
          await AddDirectorys(this.form)
          this.$message.success('添加成功')
        }
        this.closeDialog()
        this.getDirectorysList()
      })
    },
    /**
       * 新增目录
       */
    addDirectory () {
      this.showDialog = true
    },
    /**
       * 学科目录
       */
    async getSubjectsList () {
      const { data } = await getSubjects({ page: 1, pagesize: 9999 })
      this.formList = data
      // console.log(this.formList);
    },
    /**
     * 页容量变化
     */
    handleSizeChange (val) {
      this.listData.pagesize = val
      this.listData.page = 1
      this.getDirectorysList()
    },
    /**
     * 页码变化
     */
    handleCurrentChange (val) {
      this.listData.page = val
      this.getDirectorysList()
    },
    /**
     * 计算当前行的行号
     */
    indexMethod (index) {
      return (this.listData.page - 1) * this.listData.pagesize + index + 1
    },
    /**
     * 格式状态
     */
    formatterFormOfEmpment (row, column, cellValue, index) {
      return cellValue === 1 ? '已启用' : '已禁用'
    },
    /**
     * npm i dayjs 转换时间
     */
    formateTime (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    /**
     * 获取列表
     */
    async getDirectorysList () {
      const { data } = await getDirectorys(this.listData)
      this.displayList = data.items
      this.total = data.counts
    },
    /**
     * 关闭弹框
     */
    closeDialog () {
      if (this.$route.query.id) {
        this.form.directoryName = ''
      } else {
        this.form = {
          subjectID: '',
          directoryName: ''
        }
      }
      this.showDialog = false
      this.$refs.directoryForm.resetFields()
    }
  }
}
</script>

<style scoped>
    .app-container{
      padding: 0 10px;
      margin: 10px 0;
    }
   .el-header{
    padding: 0;
   }
   .switch{
    display: none;
   }
</style>
